package com.cscp.javastudy.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Demo用来理解可重入锁
 * Lock: 非公平锁，可重入锁
 */
public class LockDemo6 {
    public static void main(String[] args) {
        Phone6 phone = new Phone6();

        new Thread(()->{
            phone.sendSMS();
        },"A").start();

        new Thread(()->{
            phone.sendSMS();
        },"B").start();
    }
}

class Phone6{

    Lock lock = new ReentrantLock();

    public void sendSMS(){
        lock.lock();//lock锁必须派对存在,有加锁就一定要有解锁

        try {
            System.out.println(Thread.currentThread().getName()+" sendSMS");
            call();//这里也有锁
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void call(){
        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName()+" call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
